function ParamWN = DefParamInteractive(PluVel)
%DefParamInteractive - Interactive choice of WADENOW parameters
%
%       ParamWN = DefParamInteractive
%       ParamWN = DefParamInteractive(PluVel)
%
% This function is like DefParam, but allows the interactive choice of
% parameters to be used by WADENOW function via an input dialog box.
% If PluVel is defined, the default values of velocity thresholds and 
% standard deviations for data augmentations are defined on the basis 
% of PluVel.
%
% The output ParamWN is a struct variable whose fields are:
%
% Wavelet        : wavelet. Possible values: 'amor' (MATLAB default) and 
%                  'morlet' (analytic morlet whose Parameters can be user 
%                  defined). If a string different from 'amor' and 'morlet'
%                  is chosen, 'amor' is used.
% F0             : central frequency (cpd) of the complex oscillation 
%                  (default: 6/(2*pi), to have omega0 = 6).
% Sigmat         : Parameter of the Gussian bell with tapers the complex 
%                  oscillation (default: 1). 
%                  Note: the Parameters F0 and Sigmat are active only if 
%                  the option 'morlet' is chosen
% Fs             : sampling frequency (24 cpd, i.e. 1h sampling time)
% NPerDay        : number of scalograms (i.e. of computation times tc) per 
%                  day. The allowed values are 1 (one scalogram per day at 
%                  0h), 2 (two scalograms at 0h and 12 h), 3 (0h, 8h, 16h), 
%                  4 (0h, 6h, 12h, 18h), 6 (0h, 4h, 8h, 12h, 16h, 18h, 20h),
%                  12 (even hours), 24.
% Na             : the starting date of the scalograms related to tc(k) is
%                  tc(k)-Na, where Na is expressed in days, provided that 
%                  the segment tc(k)-Na completely belongs to the time series
%                  (if this condition is not fulfilled, the corresponding 
%                  scalogram is not computed).
% Nb             : the ending date of the rainfall scalogram related to tc(k)
%                  is tc(k)+Nb, where Nb is expressed in days, under the 
%                  condition that tc(k)+Nb completely belongs to the times
%                  series (if such a condition is not fulfilled, the 
%                  scalogram is not computed).
%                  The ending date of the velocity scalogram always is t(k). 
% Nc             : number of days to be considered before tc for the trend
%                  classification. If it is empty, it is Nc = 5.
% Nd             : number of days to be considered after tc for the trend 
%                  classification. If it is empty, it is Nd = 5.
% DateIn         : initial date for which the scalograms are computed (this
%                  date must be expressed as serial number). The start time 
%                  of the first computed scalogram is max(DateIn-Na,t(1)),
%                  where t is the time vector of the input time series. 
%                  If DateIn is undefined of empty, DateIn = t(1).
% DateFin        : final date for which the scalograms are computed (this
%                  date must be expressed as serial number). The end time 
%                  of the last computed scalogram is min(DateFin+Nb,t(end)). 
%                  If DateFin is undefined of empty, DateFin = t(end).
% Vmh            : scalar/vector/matrix for the management of thresholds for 
%                  the time series segments classification. Options:
%                  - Vmh is a scalar. in this case, 4-levels classification
%                    (including transitions) is carried out, according to: 
%                       1: L, 2: L->H, 3: H, 4: H->L, 
%                    with the threshold VH = Vmh.
%                  - Vmh is a 2-elements vector. In this case, a 7-levels
%                    classification is carried out with the thresholds 
%                    VM = Vmh(1) and VH = Vmh(2) (the vector is sorted in
%                    ascending order). The levels L, M and H are characterized
%                    by the conditions V<=M, M<V<=H and V>H respectively. The
%                    outputs are: 
%                       1: L, 2: L->M, 3: M, 4: M->H (or also L->H),
%                       5: H, 6: H->M, 7: M->L (or also H->L).
%                  - Vmh is a 2-column matrix Vmh = [t VH], where VH(h) is
%                    the time-dependent threshold at t(h), as in the first
%                    case (four level output).
%                  - Vmh is a 3-column matrix Vmh = [t VM VH], where VM(h) 
%                    and VH(h) are the time-dependent threshold at t(h), as 
%                    in the second case.
%                  In the interactive version, if H and M are both empty,
%                  the name of the file with the threshold matrix, which
%                  must have the field Vmh, can be interactively managed. 
% SigmaDA        : standard deviation of rainfall and velocity to be used
%                  in data augmentation. If length(SigmaDA) == 2, it is
%                  sigmaR = SigmaDA(1) and sigmaV = SigmaDA(2). If SigmaDA
%                  is a scalar, it is sigmaR = SigmaDA. Please note that
%                  sigmaDA must be coherent with the used signal.
%                  If sigmaDA is undefined or empty, it can be managed in
%                  an interactive way.
% CNNmodel       : allowed strings: 'alexnet', 'vgg16', 'vgg19', 'googlenet',
%                  'resnet18'. If no a correct string is chosen, the default
%                  choice 'vgg19' is used.
% SizeIm         : image size. Such a field is automatically defined on the
%                  basis of the chosen CNNmodel. 
% VectPart       : 3-elements vector such that VectPart(1) is the fraction 
%                  of images for training, VectPart(2) is the fraction for 
%                  validation and VectPart(3) is the fraction for test.
%                  The condition sum(VectPart) <= 1 must be satisfied.
%                  If vectPart is empty or the condition about sum(VectPart) 
%                  is not satisfied, VectPart = [0.7 0.15 0.15] is used.
% ComPart        : Common part of scalogram filenames (folder name, common 
%                  part of the filename). Each filename is completed with  
%                  the date string. For example, if ComPart is the string 
%                       'pluvioData\LongBeach15days', 
%                  the filename of the scalogram whose computation date is 
%                  15 march 2020, 12:00:00 is the string
%                    'pluvioData\LongBeach15days_15-Mar-2020-120000.jpg'.
%                  If comPart is empty, ComPart = '' is used. 
% FoldOut        : General folder of classified scalograms. For each level
%                  Lk (k=1:4 if Vmh is a scalar or a 2-columns matrix,  
%                  or k=1:8 if Vmh is a vector or a 3-columns matrix), a 
%                  nested folder whose name is Lk is generated and the
%                  corresponding output scalogram images are placed here.
% MiniBatchSize  : Parameter for CNN training (default: 10). 
% MaxEpoch       : Parameter for CNN training
%
% The parameter struct variable can be saved as a MATLAB .mat file. 
%
%       ParamWN = DefParamInteractive
%       ParamWN = DefParamInteractive(PluVel)
%
% See also DefParam. 

% G. Teza, 2020

if nargin < 1 || isempty(PluVel)
    Href = 0.02;
    Mref = 0.007;
    SDRref = 6;
    SDVref = 0.002;
    d1 = '';
    d2 = '';
else
    Href = max(PluVel(:,3))/5;
    Mref = Href/3;
    SDRref = nanstd(PluVel(:,2));
    SDVref = nanstd(PluVel(:,3));
    d1 = datestr(PluVel(1,1),1);
    d2 = datestr(PluVel(end,1),1);
end


%% Input dialog box

options.Resize = 'on';
options.WindowStyle = 'normal';
options.Interpreter = 'tex';

nameP = 'WADENOW PARAMETERS';

promptP = {...
    'Wavelet. Options: amor (default amor) or morlet (general amor)',...
    'Central frequency (cpd) and sigmat (d) (only applies for general amor)',...
    'Sampling frequency (cpd)',...
    'Days before and after reference date for scalogram generation:',...
    'Days before and after reference date for trend evaluation:',...
    'Scalograms per day (allowed values: 1, 2, 3, 4, 6, 12, 24):',...
    'Initial and final date for scalogram computation (dd-mmm-yyyy)',...
    'Thresholds M and H (if both empty, a matrix can be taken from a file):',...
    'Rainfall and Velocity SD for data augmentation:',...
    'CNN model (options: alexnet, vgg16, vgg19, googlenet, resnet18)',...  
    'Training - validation - test fractions (sum must be <= 1):',...
    'Common part of scalogram filenames:',...
    'General folder of classified scalograms:',...
    'MiniBatchSize for CNN training',...
    'MaxEpoch for CNN training'};

numlinesP = [1 2 1 2 2 1 2 2 2 1 3 1 1 1 1];

defaultP = {'amor',char({'',''}),'24',char({'15','2'}),...
    char({'5','5'}),'24',char({d1,d2}),...
    char({num2str(Mref),num2str(Href)}),...
    char({num2str(SDRref),num2str(SDVref)}),...
    'vgg19',...
    char({'0.7','0.15','0.15'}),'OutScalogram','OutFolder','10','10'};

answerP = inputdlg(promptP,nameP,numlinesP,defaultP,options);

Wavelet = answerP{1};

VFS = answerP{2};
if isempty(VFS)
    F0 = 6/(2*pi);
    Sigmat = 1;
else
    F0 = str2double(VFS(1,:));
    if isnan(F0), F0 = 6; end
    Sigmat = str2double(VFS(2,:));
    if isnan(Sigmat), Sigmat = 1; end
end

Fs = round(str2double(answerP{3}));
if isnan(Fs), Fs = 2; end

Nab = answerP{4};
Na = round(str2double(Nab(1,:)));
if isnan(Na), Na = 15; end
Nb = round(str2double(Nab(2,:)));
if isnan(Nb), Nb = 2; end

Ncd = answerP{5};
Nc = round(str2double(Ncd(1,:)));
if isnan(Nc), Nc = 5; end
Nd = round(str2double(Ncd(2,:)));
if isnan(Nd), Nd = 5; end

NPerDay = round(str2double(answerP{6}));
if isnan(NPerDay), NPerDay = 24; end

VD = answerP{7};
d1t = VD(1,:);
if isempty(d1t)
    DateIn = [];
else
    DateIn = round(datenum(d1t,1));
end
d2t = VD(2,:);
if isempty(d2t)
    DateFin = [];
else
    DateFin = round(datenum(d2t,1));
end

VMH = answerP{8};
if ~isempty(VMH)
    M = str2double(VMH(1,:));
    if isnan(M), M = []; end
    H = str2double(VMH(2,:));
    if isnan(H), H = []; end
    Vmh = [M H];
else
    [fileT,pathT] = uigetfile('.mat','Threhsold matrix file');
    fileT = fullfile(pathT,fileT);
    T = load(fileT);
    try
        Vmh = T.Vmh;
    catch
        disp('The selected file must contain the field Vmh');
        return
    end
end

VSD = answerP{9};
SDR = str2double(VSD(1,:));
if isnan(SDR), SDR = SDRref; end
SDV = str2double(VSD(2,:));
if isnan(SDV), SDV = SDVref; end
SigmaDA = [SDR SDV];

CNNmodel = answerP{10};

VF  = answerP{11};
FTr = str2double(VF(1,:));
if isnan(FTr), FTr = 0.7; end
FV  = str2double(VF(2,:));
if isnan(FV), FV = 0.15; end
FTe = str2double(VF(3,:));
if isnan(FTe), FTe = 0.15; end
VectPart = [FTr FV FTe];
if sum(VectPart) > 1
    VectPart = [0.7 0.15 0.15]; 
end

ComPart = answerP{12};
FoldOut = answerP{13};

MiniBatchSize = str2double(answerP{14});
if isnan(MiniBatchSize), MiniBatchSize = 10; end
MaxEpochs  = str2double(answerP{15});
if isnan(MaxEpochs), MaxEpochs = 10; end

%% Output variable generation

ParamWN.Wavelet = Wavelet;            
if ~ismember(ParamWN.Wavelet,{'amor','morlet'})
    ParamWN.Wavelet = 'amor';
end
% ParamWNeters f0 and sigmat act only is wavelet is amor   
ParamWN.F0 = F0;  
ParamWN.Sigmat = Sigmat;

ParamWN.Fs = Fs;

ParamWN.VoicesPerOctave = 24;

ParamWN.Na = Na;

ParamWN.Nb = Nb;

ParamWN.Nc = Nc;

ParamWN.Nd = Nd;

ParamWN.NPerDay = NPerDay;
if isempty(ParamWN.NPerDay)||~ismember(ParamWN.NPerDay,[1 2 3 4 6 12 24])
    ParamWN.NPerDay = 1;
end

ParamWN.DateIn = DateIn;
ParamWN.DateFin = DateFin; 

ParamWN.Vmh = Vmh;

ParamWN.SigmaDA = SigmaDA;

ParamWN.CNNmodel = CNNmodel;
chCNNmodel = lower(ParamWN.CNNmodel);
if ~ismember(chCNNmodel,{'alexnet','vgg16','vgg19','googlenet','resnet18'})
    chCNNmodel = 'vgg19';
end
ParamWN.CNNmodel = chCNNmodel;

if strcmp(chCNNmodel,'alexnet')
    SizeIm = [227 227];
else
    SizeIm = [224 224];
end
ParamWN.SizeIm = SizeIm;

ParamWN.VectPart = VectPart;

ParamWN.ComPart = ComPart;
if isempty(ParamWN.ComPart), ParamWN.ComPart = ''; end

ParamWN.FoldOut = FoldOut; 
if isempty(ParamWN.FoldOut), ParamWN.FoldOut = ''; end

ParamWN.MiniBatchSize = MiniBatchSize;
ParamWN.MaxEpochs = MaxEpochs;

mensa = menu('PARAMETER FILE SAVE',...
    'YES, WITH DEFAULT FILENAME (ParamWN.mat)',...
    'YES, WITH USER-DEFINED FILENAME',...
    'NO');
if mensa == 1
    save('ParamWN.mat','ParamWN');
elseif mensa == 2
    [fileP, pathP] = uiputfile(...
        {'*.mat','MAT-files (*.mat)'}, ...
        'SAVE PARAMETER FILE',...
        'ParamWN.mat');
    Pfile = fullfile(pathP,fileP);
    if ischar(Pfile)
        if exist(Pfile,'file')
            delete(Pfile);
        end
        save(Pfile,'ParamWN');
    else
        fprintf('\nThe data saving cannot be carried out\n');
    end
end    